// Package userdomain
// @Author zhongxc
// @Date 2023/12/12 18:08:00
// @Desc
package userdomain

import (
	"context"
	"errors"
	"github.com/zeromicro/go-zero/core/logx"
	"zhongxc.cc/admin-common/msdb"
	"zhongxc.cc/admin-common/tools"
	userdao "zhongxc.cc/admin-user/internal/dao/user"
	"zhongxc.cc/admin-user/internal/model"
	"zhongxc.cc/admin-user/internal/repo/user"
)

type SysUserDomain struct {
	sysUserRepo user.SysUserRepo
}

func NewSysUserDomain(db *msdb.MsDB) *SysUserDomain {
	return &SysUserDomain{
		sysUserRepo: userdao.NewSysUserDao(db),
	}
}

func (d *SysUserDomain) FindById(ctx context.Context, userId int64) (*model.SysUser, error) {
	userinfo, err := d.sysUserRepo.FindById(ctx, userId)
	if err != nil {
		logx.Error(err)
		return nil, errors.New("数据库异常")
	}
	return userinfo, nil
}

func (d *SysUserDomain) FindByName(ctx context.Context, username string, password string) (*model.SysUser, error) {
	userinfo, err := d.sysUserRepo.FindByName(ctx, username)
	if err != nil {
		logx.Error(err)
		return nil, errors.New("数据库异常")
	}
	if userinfo == nil {
		return nil, errors.New("用户不存在")
	}
	if tools.Base64Md5(password+userinfo.Salt) == userinfo.Password {
		return userinfo, nil
	}
	return nil, errors.New("账号或密码错误")
}
